﻿using Application.Common.Interfaces;
using Common.Attributes;
using MediatR;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using Common.Linqs;
using Domain.Entities.Loggers;
using Microsoft.EntityFrameworkCore;
using Common.Interfaces;

namespace Application.Features.Monitors.Commands.Delete;

#nullable disable

/// <summary>
/// 清空日志
/// </summary>
[Description("清空日志")]
[GroupDescription(("系统监控"))]
public class ClearLoggerCommand : IRequest<bool>
{
    /// <summary>
    /// 日志ID
    /// </summary>
    [Required(ErrorMessage = "日志ID必填")]
    public List<string> LoggerIds { get; set; }

    /// <summary>
    /// 日志类型
    /// </summary>
    [Required(ErrorMessage = "日志类型")]
    public string Type { get; set; } 
}

/// <summary>
/// 处理程序
/// </summary>
public class ClearLoggerCommandHandler : IRequestHandler<ClearLoggerCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMediator _mediator;
    private readonly ICurrentUserService _currentUserService;

    public ClearLoggerCommandHandler(
        IApplicationDbContext context, 
        IMediator mediator, 
        ICurrentUserService currentUserService)
    {
        _context = context;
        _mediator = mediator;
        _currentUserService = currentUserService;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(ClearLoggerCommand request, CancellationToken cancellationToken)
    {
        var predicate = PredicateBuilder.False<Logger>();
        foreach (var id in request.LoggerIds)
        {
            predicate = predicate.Or(l => l.Message.Contains(id));
        }

        var logsToClear = await _context.Loggers
            .Where(predicate)
            .ToListAsync(cancellationToken);

        _context.Loggers.RemoveRange(logsToClear);

        return true;
    }
}
